#include "types.h"
#include "stat.h"
#include "user.h"
#include "shmflg.h"
void WR_test()
{
  int key = 555;
  char*  name;
  int shmid;
  int pid = fork();
  if (pid >0 ) //father
  {
    name = "father";
    printf(1,"%s\n",name);
    shmid = shmget(key,3000,CREAT);
    void* shmAddf = shmat(shmid,SHM_RDWR);
    *((int*)shmAddf) = 666;
    printf(1,"father change- shared memory: %d\n",*((int*)shmAddf));
    wait();  
    printf(1,"father - shared memory: %d\n",*((int*)shmAddf));    
  }
  else //child
  {
    sleep(15);
    name = "child";
    printf(1,"%s\n",name);    
    shmid = shmget(key,200,GET);
    void* shmAdds = shmat(shmid,SHM_RDONLY);
    printf(1,"child - shared memory address: %x\n",shmAdds);
    printf(1,"child - shared memory: %d\n",*((int*)shmAdds));
    *((int*)shmAdds) = 555;
    printf(1,"child change- shared memory: %d\n",*((int*)shmAdds));    
    shmdt(shmAdds);
    exit();
  }  
}

void WW_test()
{
  int key = 123;
  char*  name;
  int shmid;
  int pid = fork();
  if (pid >0 ) //father
  {
    name = "father";
    printf(1,"%s\n",name);
    shmid = shmget(key,3000,CREAT);
    void* shmAddf = shmat(shmid,SHM_RDWR);
    *((int*)shmAddf) = 666;
    printf(1,"father change- shared memory: %d\n",*((int*)shmAddf));
    wait();
    void* x = malloc(3000);    
    *((int*)x) = 12345;
    printf(1,"father - malloc: %d\n",*((int*)x));    
    printf(1,"father - shared memory: %d\n",*((int*)shmAddf));       
    shmdt(shmAddf);
    shmdel(shmid);
  }
  else //child
  {
    sleep(15);
    name = "child";
    printf(1,"%s\n",name);    
    shmid = shmget(key,200,GET);
    void* shmAdds = shmat(shmid,SHM_RDWR);
    printf(1,"child - shared memory: %d\n",*((int*)shmAdds));
    *((int*)shmAdds) = 555;
    printf(1,"child change- shared memory: %d\n",*((int*)shmAdds));    
    shmdt(shmAdds);
    exit();
  }
}

void deattch_test()
{    
  int key = 11;
  int shmid = shmget(key,200,CREAT);
  void* shmAddf = shmat(shmid,SHM_RDWR);
  *((int*)shmAddf) = 666;
  printf(1,"father change- shared memory: %d\n",*((int*)shmAddf));
  shmdt(shmAddf);
  printf(1,"father after deattch- shared memory: %d\n",*((int*)shmAddf));
  shmdel(shmid);
}

void swappingTest()
{
  void* x = malloc(6000);
  *((int*)x) = 6;
 int pid = fork();
  if (pid >0) //father
  {
    enableSwapping();
    sleep(30);
    disableSwapping();    
    wait();
  }
  else  //son
  {
    sleep(5);
    uint i;
    for (i=0; i<10; ++i)
    {
      printf(1,"%d\n",*((int*)x));
      sleep(1);
    }
  } 
}

int main(void)
{
 /*printf(1,"write write test\n");
 WW_test(); */
  printf(1,"swapping test\n");
 swappingTest();

 /* printf(1,"deattch test\n");
 deattch_test();
 printf(1,"write readonly test\n");
 WR_test();*/
 exit();
}